package pw.mcdarc.mc.bython;

import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import pw.mcdarc.mc.bython.Command.CommandExecutor;
import pw.mcdarc.mc.bython.Pool.TempStore;
import pw.mcdarc.mc.bython.Util.FileUtil;
import pw.mcdarc.mc.bython.Util.eventList;
import pw.mcdarc.mc.bython.Asm.ListenerClassBuilder;
import pw.mcdarc.mc.bython.SQL.MYSQL;
import pw.mcdarc.mc.bython.SQL.SQLite;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.IOException;
import java.util.*;

/*
This file is part of Bython.
Dont remove this header anytime.
Under the Apache2 License.
You can't sell it, repost it, share it without permission.
Date: 八月,27,2016
*/

public class Bython extends JavaPlugin {

    public static File dataFolder;
    public static Bython i;
    public static String nmsPackageName;
    public static ArrayList<File> LoadedFiles = new ArrayList<>();
    public static HashMap<String, String> Events = new HashMap<>();
    public static Set<String> list = new HashSet<>();
    public static HashMap<String, MYSQL> MYSQLs = new HashMap<>();
    public static HashMap<String, SQLite> SQLites = new HashMap<>();

    public void onLoad() {
        i = this;
    }

    /**
     * 需要在onEnable时对脚本是否可运行做测试
     */
    public void onEnable() {
        dataFolder = getDataFolder();
        if (!dataFolder.exists()) {
            if (!dataFolder.mkdir()) {
                getLogger().warning("错误: plugins文件夹下权限异常");
            }
        }
//        list.add("org.bukkit.event.player.PlayerLoginEvent");
//        list.add("org.bukkit.event.player.PlayerJoinEvent");

        // 验证脚本
        nmsPackageName = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
        ArrayList<File> scriptFiles = FileUtil.getListFiles(getDataFolder());
        for (File file : scriptFiles) {
            // 读文本并检查是否为脚本文件
            String s = "";
            try {
                s = FileUtils.readFileToString(file);
            } catch (IOException e) {
                getLogger().warning("无法读取脚本文件\n" + e.getMessage());
            }
            if (s.isEmpty()) {
                continue;
            }
            ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
            try {
                engine.put("pool", new TempStore());
                engine.eval(s);
                engine.eval("onLoad()");
                String events = (String)engine.get("_event_");
                String[] events2 = events.split(" and ");
                if (!events.equals("")) {
                    for (String s2 : events2) {
                        String[] events3 = s2.split("-");
                        Events.put(events3[0], events3[1]);
                        eventList.add(events3[0]);
                    }
                }
            } catch (ScriptException e) {
                e.printStackTrace();
                continue;
            }
            LoadedFiles.add(file);
            // 判断结束 应该在LoadedFiles里有了头是正确的脚本文件了
            // 由于获取文件使用了递归的方式, 所以可以在PyInterface目录下建立子文件夹来存放脚本
        }
        ListenerClassBuilder builder = new ListenerClassBuilder("BythonEventListener",list,getClassLoader());
        builder.generate();
//        builder.save(new File("C:/Development/TEST.class"));
        Class c = builder.loadClass();
        try {
            getServer().getPluginManager().registerEvents((Listener) c.newInstance(),this);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        getLogger().info(LoadedFiles.size() + "个脚本文件已加载");
        Bukkit.getPluginCommand("bython").setExecutor(new CommandExecutor(this));
        getLogger().info("加载成功");
    }

    public void onDisable() {
    }
}
